package com.liyuncong.algorithm.algorithm_kmeans.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.liyuncong.algorithm.algorithm_similarity.entity.Vector;

public class VectorsUtil {
	public static List<Vector> loadVectorList(String fileName) {
		Charset charset = Charset.forName("UTF-8");
		return loadVectorList(fileName, charset);
	}
	
	/**
	 * 加载向量集合;
	 * 向量通过换行符隔开，
	 * 向量的元素间通过逗号隔开；
	 * @param fileName 文件名
	 * @param charset 字符集
	 * @return
	 */
	public static List<Vector> loadVectorList(String fileName, Charset charset) {
		List<Vector> vectorList = new ArrayList<Vector>();
		try(InputStream inputStream = new FileInputStream(fileName);
				Reader reader = new InputStreamReader(
						inputStream, charset)) {
			StringBuffer vectorsStrBuf = new StringBuffer();
			char[] cbuf = new char[4096];
			int size = 0;
			while ((size = reader.read(cbuf)) != -1) {
				for(int i = 0; i < size; i++) {
					vectorsStrBuf.append(cbuf[i]);
				}
			}
			String vectorsStr = vectorsStrBuf.toString();
			// 用换行符分割字符串，得到事务数组
			String[] vectorsArr = vectorsStr.split(
					System.lineSeparator());
			for(String itemsStr : vectorsArr) {
				// 用英文或者中文逗号分隔字符串，得到项的数组
				String[] itemsArr = itemsStr.split("[,，]");
				int itemNum = itemsArr.length;
				float[] elements = new float[itemNum];
				for(int i= 0; i < itemNum; i++) {
					elements[i] = Float.valueOf(itemsArr[i]);
				}
				Vector vector = new Vector(elements);
				vectorList.add(vector);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return vectorList;
	}
}
